package com.hk.core.web.interceptors;

import com.hk.commons.util.CollectionUtils;
import com.hk.core.web.Webs;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * 属性拦截器，将Map 属性保存到request中
 *
 * @author Kevin
 * @date 2018-11-30 09:27
 */
public class GlobalPropertyInterceptor implements AsyncHandlerInterceptor {

    private static final String CONTEXT_PATH = "contextPath";

    /**
     * request 中的属性
     */
    private final Map<String, Object> property = new HashMap<>();

    public void setProperty(Map<String, Object> property) {
        if (CollectionUtils.isNotEmpty(property)) {
            this.property.putAll(property);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        property.forEach(request::setAttribute);
        request.setAttribute(CONTEXT_PATH, request.getContextPath());
        ServletRequestAttributes requestAttribute = Webs.getRequestAttribute();
        // 在异步中，获取不到request，将 requestAttributes 放在 NamedInheritableThreadLocal 中上
        RequestContextHolder.setRequestAttributes(requestAttribute, true);
        return true;
    }
}
